<template>
  <div class="h-screen bg-gradient-to-br from-purple-50 via-indigo-50 to-blue-50 flex flex-col overflow-hidden">
    <!-- 导航栏 -->
    <NavBar :showDashboard="true" />

    <!-- 主要内容 -->
    <div class="flex-1 py-6 px-4 sm:px-6 lg:px-8 overflow-hidden">
      <div class="w-full max-w-[98%] mx-auto h-full flex flex-col">
        <!-- 页面标题和操作栏 -->
        <div class="mb-6 flex-shrink-0">
          <div class="flex items-center justify-between">
            <div>
              <h1 class="text-3xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-purple-600 via-indigo-600 to-blue-600">
                {{ document?.title }}
              </h1>
              <div class="flex items-center gap-4 mt-2">
                <p class="text-gray-600">正在进行{{ getStepText(document?.step) }}</p>
                <!-- 本地草稿状态指示 -->
                <div v-if="hasLocalDraft" class="flex items-center gap-2 text-sm">
                  <div class="w-2 h-2 bg-orange-400 rounded-full"></div>
                  <span class="text-orange-600">
                    本地草稿 {{ formatDraftTime(localDraftTime) }}
                  </span>
                </div>
              </div>
            </div>
            <div class="flex items-center gap-4">
              <!-- 校对进度状态 -->
              <div class="flex items-center gap-3">
                <div class="flex h-3 rounded-full overflow-hidden w-48 bg-gray-200 relative">
                  <!-- 分段标记线 -->
                  <div class="absolute inset-0 flex w-full">
                    <div class="w-1/3 h-full border-r border-white/50"></div>
                    <div class="w-1/3 h-full border-r border-white/50"></div>
                    <div class="w-1/3 h-full"></div>
                  </div>
                  
                  <!-- 第一阶段 -->
                  <div 
                    class="h-full bg-blue-500 transition-all duration-300"
                    :class="{ 'opacity-30': document?.step === 0 }"
                    :style="{ width: getStepProgress(document?.step, 1) }"
                  ></div>
                  <!-- 第二阶段 -->
                  <div 
                    class="h-full bg-purple-500 transition-all duration-300"
                    :class="{ 'opacity-30': document?.step < 2 }"
                    :style="{ width: getStepProgress(document?.step, 2) }"
                  ></div>
                  <!-- 第三阶段 -->
                  <div 
                    class="h-full bg-green-500 transition-all duration-300"
                    :class="{ 'opacity-30': document?.step < 3 }"
                    :style="{ width: getStepProgress(document?.step, 3) }"
                  ></div>
                </div>
                
                <!-- 进度描述 -->
                <span 
                  class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap"
                  :class="{
                    'bg-gray-100 text-gray-800': document?.step === 0,
                    'bg-blue-100 text-blue-800': document?.step === 1,
                    'bg-purple-100 text-purple-800': document?.step === 2,
                    'bg-green-100 text-green-800': document?.step === 3
                  }"
                >
                  {{ getStepText(document?.step) }}
                </span>
              </div>
              
              <!-- 操作按钮 -->
              <div class="flex gap-3">
                <button
                  @click="handleSave"
                  class="px-4 py-2 bg-indigo-100 text-indigo-700 rounded-lg hover:bg-indigo-200 transition-colors duration-200 flex items-center gap-2 relative"
                >
                  <SaveIcon className="w-4 h-4" />
                  保存草稿
                  <!-- 保存成功提示 -->
                  <span 
                    v-if="showSaveSuccess"
                    class="absolute -top-8 left-1/2 transform -translate-x-1/2 bg-green-600 text-white text-xs px-2 py-1 rounded whitespace-nowrap z-10"
                  >
                    已保存到本地
                  </span>
                </button>
                <button
                  @click="handleComplete"
                  class="px-4 py-2 bg-green-100 text-green-700 rounded-lg hover:bg-green-200 transition-colors duration-200 flex items-center gap-2"
                >
                  <CheckCircleIcon className="w-4 h-4" />
                  提交校对
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 校对工作区 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 flex-1 min-h-0">
          <!-- 左侧原文显示 -->
          <div class="bg-white/60 backdrop-blur-sm rounded-xl border border-purple-100/20 shadow-lg overflow-hidden flex flex-col h-full">
            <div class="bg-gray-50/50 px-6 py-4 border-b border-purple-100/20 flex-shrink-0">
              <h2 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
                <DocumentIcon className="w-5 h-5 text-indigo-600" />
                原文内容
              </h2>
              <p class="text-sm text-gray-500 mt-1">请参照原文进行校对编辑</p>
            </div>
            <div class="flex-1 p-6 overflow-y-auto min-h-0">
              <div class="prose max-w-none prose-indigo">
                <div class="whitespace-pre-wrap font-mono text-gray-700 leading-relaxed text-sm">
                  {{ document?.content }}
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧Markdown编辑器 -->
          <div class="bg-white/60 backdrop-blur-sm rounded-xl border border-purple-100/20 shadow-lg overflow-hidden flex flex-col h-full">
            <div class="bg-gray-50/50 px-6 py-4 border-b border-purple-100/20 flex-shrink-0">
              <h2 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
                <EditIcon className="w-5 h-5 text-purple-600" />
                校对编辑
              </h2>
              <p class="text-sm text-gray-500 mt-1">
                支持 Markdown 语法，使用 # 添加标题，* 或 _ 添加强调，> 添加引用等
              </p>
            </div>
            <div class="flex-1 p-6 min-h-0">
              <div class="h-full border border-purple-100/20 rounded-lg overflow-hidden">
                <div ref="editorRef" class="h-full" style="min-height: 300px;"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 提交确认对话框 -->
    <AlertDialog v-model:open="isConfirmDialogOpen">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>确认提交校对</AlertDialogTitle>
          <AlertDialogDescription>
            您确定要提交《{{ document?.title }}》的{{ getStepText(document?.step) }}结果吗？
            提交后文档将进入下一个校对阶段，无法再次编辑当前阶段的内容。
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel @click="isConfirmDialogOpen = false">取消</AlertDialogCancel>
          <AlertDialogAction @click="confirmComplete">确定提交</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getDocument, updateDocument } from '../api/document'
import { Crepe } from "@milkdown/crepe"
import "@milkdown/crepe/theme/common/style.css"
import "@milkdown/crepe/theme/frame.css"
import CheckCircleIcon from '../components/icons/CheckCircleIcon.vue'
import SaveIcon from '../components/icons/SaveIcon.vue'
import DocumentIcon from '../components/icons/DocumentIcon.vue'
import EditIcon from '../components/icons/EditIcon.vue'
import NavBar from '../components/NavBar.vue'
import { 
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader, 
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogAction,
  AlertDialogCancel
} from '../components/ui/alert-dialog'

const route = useRoute()
const router = useRouter()
const document = ref(null)
const editorRef = ref(null)
const isConfirmDialogOpen = ref(false)
const showSaveSuccess = ref(false)
const hasLocalDraft = ref(false)
const localDraftTime = ref(null)
let editor = null

// 获取步骤文本
const getStepText = (step) => {
  const stepTexts = {
    0: '未开始',
    1: '第一次校对',
    2: '第二次校对',
    3: '第三次校对'
  }
  return stepTexts[step] || '未知状态'
}

// 计算每个阶段的进度宽度
const getStepProgress = (step, currentStep) => {
  // 如果文档还未开始(step=0)，则所有段显示为0%
  if (step === 0) {
    return '0%'
  }
  
  // 每个阶段占总进度条的1/3
  const stageWidth = 33.33
  
  // 如果当前文档步骤小于传入的step，则此段为0%
  if (step < currentStep) {
    return '0%'
  }
  
  // 如果当前步骤等于传入的step，则根据当前进度计算
  if (step === currentStep) {
    const basePercent = (currentStep - 1) * stageWidth
    const currentPercent = document.value?.process - basePercent
    const segmentWidth = Math.min(currentPercent, stageWidth)
    return `${segmentWidth}%`
  }
  
  // 如果当前步骤大于传入的step，则此段已完成
  return `${stageWidth}%`
}

// 检查本地草稿状态
const checkLocalDraft = (docId, step) => {
  const localDraftKey = `proofread_draft_${docId}_step_${step}`
  const timestampKey = `proofread_draft_time_${docId}_step_${step}`
  
  const draft = localStorage.getItem(localDraftKey)
  const timestamp = localStorage.getItem(timestampKey)
  
  hasLocalDraft.value = !!draft
  localDraftTime.value = timestamp ? new Date(timestamp) : null
  
  return draft
}

// 格式化本地草稿时间
const formatDraftTime = (time) => {
  if (!time) return ''
  const now = new Date()
  const diff = now - time
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  return time.toLocaleDateString()
}

// 初始化编辑器
const initEditor = async (content) => {
  // 确保编辑器容器存在且已挂载
  if (!editorRef.value) {
    console.warn('编辑器容器尚未准备好')
    return
  }

  try {
    editor = new Crepe({
      root: editorRef.value,
      defaultValue: content || '',
      theme: 'light'
    })

    await editor.create()
    
    // 确保编辑器正确聚焦和渲染
    setTimeout(() => {
      if (editor && editor.action) {
        editor.action((ctx) => {
          // 强制重新渲染编辑器
          const view = ctx.get('editorViewCtx')
          if (view) {
            view.focus()
            
            // 添加点击事件监听器，确保光标正确定位
            const editorDom = view.dom
            if (editorDom) {
              editorDom.addEventListener('mousedown', (e) => {
                // 确保点击事件能正确传递到编辑器
                setTimeout(() => {
                  view.focus()
                }, 10)
              })
            }
          }
        })
      }
    }, 100)
  } catch (error) {
    console.error('编辑器初始化失败:', error)
  }
}

// 获取文档内容
const fetchDocument = async () => {
  try {
    const docId = route.params.id
    const response = await getDocument(docId)
    document.value = response.data
    
    // 检查本地是否有保存的草稿
    const localDraft = checkLocalDraft(docId, response.data.step)
    
    // 延迟初始化编辑器，确保DOM完全渲染
    await nextTick()
    
    // 优先使用本地草稿，如果没有则使用服务器内容
    const editorContent = localDraft || response.data.proofread_content || ''
    await initEditor(editorContent)
  } catch (error) {
    console.error('获取文档失败:', error)
  }
}

// 保存草稿到本地
const handleSave = () => {
  try {
    const content = editor.getMarkdown()
    const docId = document.value.id
    const step = document.value.step
    
    // 生成本地存储的key，包含文档ID和当前步骤
    const localDraftKey = `proofread_draft_${docId}_step_${step}`
    
    // 保存到localStorage
    localStorage.setItem(localDraftKey, content)
    
    // 保存时间戳
    const timestampKey = `proofread_draft_time_${docId}_step_${step}`
    const now = new Date()
    localStorage.setItem(timestampKey, now.toISOString())
    
    // 更新状态
    hasLocalDraft.value = true
    localDraftTime.value = now
    
    // 显示保存成功提示
    showSaveSuccess.value = true
    setTimeout(() => {
      showSaveSuccess.value = false
    }, 2000)
  } catch (error) {
    console.error('保存草稿失败:', error)
  }
}

// 清除本地草稿
const clearLocalDraft = () => {
  const docId = document.value.id
  const step = document.value.step
  const localDraftKey = `proofread_draft_${docId}_step_${step}`
  const timestampKey = `proofread_draft_time_${docId}_step_${step}`
  
  localStorage.removeItem(localDraftKey)
  localStorage.removeItem(timestampKey)
  
  // 重置状态
  hasLocalDraft.value = false
  localDraftTime.value = null
}

// 完成校对
const handleComplete = () => {
  isConfirmDialogOpen.value = true
}

// 确认完成校对
const confirmComplete = async () => {
  try {
    const content = editor.getMarkdown()
    
    await updateDocument(document.value.id, {
      content: content,
      step: document.value.step + 1
    })
    
    // 提交成功后清除本地草稿
    clearLocalDraft()
    
    isConfirmDialogOpen.value = false
    router.push('/dashboard')
  } catch (error) {
    console.error('完成校对失败:', error)
  }
}

onMounted(() => {
  fetchDocument()
})

onBeforeUnmount(() => {
  if (editor) {
    editor.destroy()
  }
})
</script>

<style>
.milkdown {
  @apply h-full bg-white/60 backdrop-blur-sm;
  overflow: hidden;
  position: relative;
}

.milkdown .editor {
  @apply h-full p-4;
  overflow-y: auto;
  max-height: 100%;
  font-size: 14px;
  line-height: 1.6;
  cursor: text;
  position: relative;
  z-index: 1;
}

.milkdown .editor:focus {
  @apply outline-none;
}

/* 确保编辑器内容区域可以正确接收点击事件 */
.milkdown .editor .ProseMirror {
  outline: none;
  cursor: text;
  min-height: 100%;
  padding: 0;
  position: relative;
}

/* 确保光标可见 */
.milkdown .editor .ProseMirror-focused {
  outline: none;
}

.milkdown .editor .ProseMirror .ProseMirror-cursor {
  pointer-events: none;
  position: absolute;
  border-left: 1px solid black;
  border-right: 1px solid transparent;
  margin-left: -1px;
  animation: cursor-blink 1.2s infinite;
}

@keyframes cursor-blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.milkdown .editor p {
  @apply my-2;
  min-height: 1.5em;
}

.milkdown .editor h1,
.milkdown .editor h2,
.milkdown .editor h3,
.milkdown .editor h4,
.milkdown .editor h5,
.milkdown .editor h6 {
  @apply font-bold text-gray-900 mt-4 mb-2;
}

.milkdown .editor h1 {
  @apply text-2xl;
}

.milkdown .editor h2 {
  @apply text-xl;
}

.milkdown .editor h3 {
  @apply text-lg;
}

.milkdown .editor ul,
.milkdown .editor ol {
  @apply my-2 pl-6;
}

.milkdown .editor ul {
  @apply list-disc;
}

.milkdown .editor ol {
  @apply list-decimal;
}

.milkdown .editor blockquote {
  @apply border-l-4 border-gray-300 pl-4 my-2 italic;
}

.milkdown .editor code {
  @apply bg-gray-100 px-1 py-0.5 rounded text-sm font-mono;
}

.milkdown .editor pre {
  @apply bg-gray-100 p-4 rounded my-2 overflow-x-auto;
}

.milkdown .editor pre code {
  @apply bg-transparent p-0;
}

.milkdown .editor a {
  @apply text-indigo-600 hover:text-indigo-500;
}

.milkdown .editor img {
  @apply max-w-full rounded;
}

.milkdown .editor table {
  @apply w-full border-collapse my-2;
}

.milkdown .editor th,
.milkdown .editor td {
  @apply border border-gray-300 px-4 py-2;
}

.milkdown .editor th {
  @apply bg-gray-100;
}
</style> 